package com.zwj.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zwj.dto.UserType;
import com.zwj.entity.UserEntity;
import com.zwj.enums.ErrorEnum;
import com.zwj.enums.ValidEnum;
import com.zwj.mapper.UserMapper;
import com.zwj.utils.TokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 拦截器
 */
public class Interceptor  implements HandlerInterceptor {
    private final UserMapper userMapper;
    List<String> paths = UserType.getPaths();
    public Interceptor(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("拦截器执行");
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        String uri = request.getRequestURI();
        // 从路由中匹配访问该路由需要的用户类型权限
        // 访问的原则是，当路由中包含admin、student、teacher时，则需要对应的session认证
        String pathUserType = noMatchUserType(uri);

        // 该路由不包含需要认证
        if (pathUserType == null) {
            return true;
        }
        final String token = request.getHeader("Authorization");
        if(StringUtils.isNotBlank(token)&&TokenUtils.checkToken(token)){
            UserEntity userEntity = TokenUtils.getUser(request);
            QueryWrapper<UserEntity> sectionQueryWrapper = new QueryWrapper<>();
            sectionQueryWrapper.lambda().eq(UserEntity::getId,userEntity.getId() )
                    .eq(UserEntity::getRoleType, userEntity.getRoleType());
            UserEntity userEntity1 = userMapper.selectOne(sectionQueryWrapper);
            if(!userEntity1.getDelFlag().equals(ValidEnum.EFFECTIVE.getKey())){
                throw  new BizException(ErrorEnum.SIGNATURE_NOT_MATCH.getResultCode(),"用户已停用！");
            }
            if(userEntity1.getLoginToken()==null||!userEntity1.getLoginToken().equals(token)){
                throw  new BizException(ErrorEnum.SIGNATURE_NOT_MATCH.getResultCode(),"用户签名认证失败!");
            }
            if (!UserType.userAuthentication(uri,pathUserType,userEntity.getRoleType())){
                throw  new BizException(ErrorEnum.SIGNATURE_NOT_MATCH.getResultCode(),"用户权限不足!");
            }
            return true;
        }
        throw  new BizException(ErrorEnum.SIGNATURE_NOT_MATCH.getResultCode(),"你没有登录，无权进行此操作!");
//        return false;//如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
        //如果设置为true时，请求将会继续执行后面的操作
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
//         System.out.println("执行了TestInterceptor的postHandle方法");
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//        System.out.println("执行了TestInterceptor的afterCompletion方法");
    }
    private String noMatchUserType(String uri) {
        String[] urlPaths =  uri.split("/");
        if(urlPaths.length<2){
            return null;
        }
        if(urlPaths.length>2){
            if(urlPaths[2].equals("selectCourse")){
                return null;
            }
        }
        for(String path:paths){
            if(path.equals(urlPaths[1])){
                return urlPaths[1];
            }
        }

        return  null;
    }
}
